package com.byxy.util;


import com.byxy.util.FileUtil;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：
 * @ClassName ：FileServiceImpl
 * @date : 2019/4/3 10:05
 * @description : TODO
 */
@Service
public class FileUtilImpl implements FileUtil {

    private String fileName = null;

    public StringMap getPutPolicy() {
        return putPolicy;
    }

    public void setPutPolicy(StringMap putPolicy) {
        this.putPolicy = putPolicy;
    }

    @Resource
    private UploadManager uploadManager;
    @Resource
    private BucketManager bucketManager;

    @Resource
    private Auth auth;


    @Value("${qiniu.bucket}")
    private String bucket;


    private StringMap putPolicy = new StringMap();


    @Override
    public Map uploadFile(File file, String fileName) throws QiniuException {
        Map map = new HashMap();
        this.fileName = fileName;
        Response response = this.uploadManager.put(file, fileName, getUploadToken());
        //解析上传的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

        String imageName = putRet.key;
        int retry = 0;
        while (response.needRetry() && retry < 3) {
            response = this.uploadManager.put(file, null, getUploadToken());
        }
        map.put("response", response);
        map.put("imgName", imageName);
        return map;
    }

    @Override
    public void deleteFileFromQiniu(String fileName) {
        try {
            bucketManager.delete(bucket,fileName);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }


    @Override
    public String getUploadToken() {


        return this.auth.uploadToken(bucket, null, 3600, putPolicy);
    }

}
